﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Collections;

namespace Untity
{
    /// <summary>
    /// 缓存操作类
    /// </summary>
    public class CacheHelper
    {
        private static readonly System.Web.Caching.Cache _cache;

        static CacheHelper()
        {
            HttpContext current = HttpContext.Current;
            if (current != null)
            {
                _cache = current.Cache;
            }
            else
            {
                _cache = HttpRuntime.Cache;
            }
        }

        #region 获取当前应用程序指定CacheKey的Cache值
        /// <summary>
        /// 获取当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <returns></returns>
        public static object GetCache(string CacheKey)
        {
            return _cache[CacheKey];
        }
        #endregion

        #region 设置当前应用程序指定CacheKey的Cache值
        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        public static void SetCache(string CacheKey, object objObject)
        {
            _cache.Insert(CacheKey, objObject);
        }
        #endregion

        #region 设置当前应用程序指定CacheKey的Cache值
        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        public static void SetCache(string CacheKey, object objObject, DateTime absoluteExpiration, TimeSpan slidingExpiration)
        {
            _cache.Insert(CacheKey, objObject, null, absoluteExpiration, slidingExpiration);
        }
        /// <summary>
        /// 设置当前应用程序指定CacheKey的Cache值
        /// </summary>
        /// <param name="CacheKey"></param>
        /// <param name="objObject"></param>
        /// <param name="CacheHours"></param>
        public static void SetCache(string CacheKey, object objObject, int CacheHours)
        {
            _cache.Insert(CacheKey, objObject, null, DateTime.Now.AddHours(CacheHours), TimeSpan.Zero);
        }
        #endregion

        #region 清除所有Cache
        /// <summary>
        /// 清除所有Cache
        /// </summary>
        public static void ClearCache()
        {
            IDictionaryEnumerator enumerator = _cache.GetEnumerator();
            while (enumerator.MoveNext())
            {
                _cache.Remove(enumerator.Key.ToString());
            }
        }
        #endregion

        #region 清除某一个key值
        /// <summary>
        /// 清除某一个key值
        /// </summary>
        public static void Remove(string key)
        {
            _cache.Remove(key);
        }
        #endregion
    }
}
